import json
import pytz
import sys
from datetime import datetime as dt

from json_templates import clpaper_template, clpaper_highlight_template, clpaper_classify_template, clpaper_republish_template
from request import get_req, post_req, patch_req
from config import config


def create_papers_highlight(open_id, data, config, receiver="open_id", today=dt.now().astimezone(pytz.timezone('Asia/Shanghai')), user=None):
    url = "https://open.feishu.cn/open-apis/doc/v2/create"
    headers = {
        "Authorization": "Bearer " + config.tenant_access_token(),
        "Content-Type": "application/json; charset=utf-8"
    }
    title = f'{today.strftime("%m{}%d{}")}arXiv论文推荐'.format("月", "日")
    req_body = clpaper_highlight_template(title, data)
    rsp_dict = post_req(url, headers, req_body)
    code = rsp_dict.get("code", -1)
    data = rsp_dict.get("data")
    if code == 0:
        href = data.get("url")
        print(href)
        jsonObjects = [
            [
                {
                    "tag": "a",
                    "href": href,
                    "text": title
                }
            ]
        ]
        # set_user_editable(data["objToken"], "ou_7fd3ab84d15e9d3e6f95e475bc7ea76b", config)
        for chat in open_id:
            notify_user(chat, jsonObjects, config, receiver=receiver)
        if not user is None:
            for u in user:
                notify_user(u['openId'], jsonObjects, config)
        return href, title
    else:
        # with open('D:\\代码生成\\arXivPost\\document.txt', 'w') as f:
        #     f.write(str(req_body))
        # print(req_body)
        print("Error!", rsp_dict.get("msg"))


def create_papers_classification(open_id, class_list, config, receiver="open_id", today=dt.now().astimezone(pytz.timezone('Asia/Shanghai')), user=None):
    url = "https://open.feishu.cn/open-apis/doc/v2/create"
    headers = {
        "Authorization": "Bearer " + config.tenant_access_token(),
        "Content-Type": "application/json; charset=utf-8"
    }
    title = f'{today.strftime("%m{}%d{}")}arXiv论文推荐'.format("月", "日")
    req_body = clpaper_classify_template(title, class_list)
    rsp_dict = post_req(url, headers, req_body)
    generate_another_for_chief_hang(title, headers, req_body, config)
    code = rsp_dict.get("code", -1)
    data = rsp_dict.get("data")
    if code == 0:
        href = data.get("url")
        print(href)
        jsonObjects = [
            [
                {
                    "tag": "a",
                    "href": href,
                    "text": title
                }
            ]
        ]
        # set_user_editable(data["objToken"], "ou_7fd3ab84d15e9d3e6f95e475bc7ea76b", config)
        for chat in open_id:
            notify_user(chat, jsonObjects, config, receiver=receiver)
        if not user is None:
            for u in user:
                notify_user(u['openId'], jsonObjects, config)
        return href, title
    else:
        # with open('D:\\代码生成\\arXivPost\\document.txt', 'w') as f:
        #     f.write(str(req_body))
        # print(req_body)
        print("Error!", rsp_dict.get("msg"))


def create_papers_republic(open_id, data, doc_list, config, receiver="open_id", today=dt.now().astimezone(pytz.timezone('Asia/Shanghai')), user=None):
    url = "https://open.feishu.cn/open-apis/doc/v2/create"
    headers = {
        "Authorization": "Bearer " + config.tenant_access_token(),
        "Content-Type": "application/json; charset=utf-8"
    }
    title = f'{today.strftime("%m{}%d{}")}——本周arXiv论文推荐'.format("月", "日")
    req_body = clpaper_republish_template(title, data, doc_list)
    rsp_dict = post_req(url, headers, req_body)
    generate_another_for_chief_hang(title, headers, req_body, config)
    code = rsp_dict.get("code", -1)
    data = rsp_dict.get("data")
    if code == 0:
        href = data.get("url")
        print(href)
        jsonObjects = [
            [
                {
                    "tag": "a",
                    "href": href,
                    "text": title
                }
            ]
        ]
        # set_user_editable(data["objToken"], "ou_7fd3ab84d15e9d3e6f95e475bc7ea76b", config)
        for chat in open_id:
            notify_user(chat, jsonObjects, config, receiver=receiver)
        if not user is None:
            for u in user:
                notify_user(u['openId'], jsonObjects, config)
        return href, title
    else:
        # with open('D:\\代码生成\\arXivPost\\document.txt', 'w') as f:
        #     f.write(str(req_body))
        # print(req_body)
        print("Error!", rsp_dict.get("msg"))


def create_papers(open_id, data, config, receiver="open_id", today=dt.now().astimezone(pytz.timezone('Asia/Shanghai'))):
    url = "https://open.feishu.cn/open-apis/doc/v2/create"
    headers = {
        "Authorization": "Bearer " + config.tenant_access_token(),
        "Content-Type": "application/json; charset=utf-8"
    }
    title = f'{today.strftime("%m{}%d{}")}arXiv论文推荐'.format("月", "日")
    req_body = clpaper_template(title, data)
    rsp_dict = post_req(url, headers, req_body)
    code = rsp_dict.get("code", -1)
    data = rsp_dict.get("data")
    if code == 0:
        href = data.get("url")
        print(href)
        jsonObjects = [
            [
                {
                    "tag": "a",
                    "href": href,
                    "text": title
                }
            ]
        ]
        # set_user_editable(data["objToken"], "ou_7fd3ab84d15e9d3e6f95e475bc7ea76b", config)
        for chat in open_id:
            notify_user(chat, jsonObjects, config, receiver=receiver)
        return href, title
    else:
        print(req_body)
        # print("Error!", rsp_dict.get("msg"))

def notify_user(openId, jsonObjects, config, type="post", receiver="open_id"):
    url = f"https://open.feishu.cn/open-apis/im/v1/messages?receive_id_type={receiver}"
    headers = {
        "Authorization": "Bearer " + config.tenant_access_token(),
        "Content-Type": "application/json; charset=utf-8"
    }
    req_body = None
    if type == "post":
        req_body = {
            "receive_id": openId,
            "content": json.dumps({
                "zh_cn": {
                    "content": jsonObjects
                }
            }),
            "msg_type": type
        }
    elif type == "text":
        req_body = {
            "receive_id": openId,
            "content": json.dumps(jsonObjects),
            "msg_type": type
        }
        
    rsp_dict = post_req(url, headers, req_body)
    print(rsp_dict)

def show_group_chat(config):
    url = "https://open.feishu.cn/open-apis/im/v1/chats"
    headers = {
        "Authorization": "Bearer " + config.tenant_access_token(),
        "Content-Type": "application/json; charset=utf-8"
    }
    
    rsp_dict = get_req(url, headers)
    if rsp_dict.get("code", -1):
        config.tenant_access_token(True)
        return show_group_chat(config)
    return [e['chat_id'] for e in rsp_dict.get('data').get('items')]

def set_user_editable(objToken, open_id, config):
    url = f"https://open.feishu.cn/open-apis/drive/v1/permissions/{objToken}/members?type=doc"
    headers = {
        "Authorization": "Bearer " + config.tenant_access_token(),
        "Content-Type": "application/json; charset=utf-8"
    }
    req_body = {
        "member_type": "openid",
        "member_id": open_id,
        "perm": "edit"
    }
    rsp_dict = post_req(url, headers, req_body)
    is_success = rsp_dict.get("data").get("is_success")
    return is_success

def copy_file(objToken, name, config, folder_token="EC6gfLPBql3jJqdICv1c1Ywxnzh"):
    url = f"https://open.feishu.cn/open-apis/drive/v1/files/{objToken}/copy"
    headers = {
        "Authorization": "Bearer " + config.tenant_access_token(),
        "Content-Type": "application/json; charset=utf-8"
    }
    req_body = {
        "name": name,
        "folder_token": folder_token,
    }
    rsp_dict = post_req(url, headers, req_body)
    if rsp_dict.get("code") == 0:
        return rsp_dict.get("data").get("file")
    else:
        return "failed"

def update_file_open(objToken, config, doc_type="doc"):
    url = f"https://open.feishu.cn/open-apis/drive/v2/permissions/{objToken}/public?type={doc_type}"
    headers = {
        "Authorization": "Bearer " + config.tenant_access_token(),
        "Content-Type": "application/json; charset=utf-8"
    }
    req_body = {
        "external_access_entity": "open",
        "security_entity": "anyone_can_view",
        "comment_entity": "anyone_can_view",
        "copy_entity": "anyone_can_view",
        "link_share_entity": "anyone_readable"
    }
    rsp_dict = patch_req(url, headers, req_body)
    is_success = (rsp_dict.get("code") == 0)
    return is_success

def generate_another_for_chief_hang(title, headers, req_body, config):
    url = "https://open.feishu.cn/open-apis/doc/v2/create"
    headers = {
        "Authorization": "Bearer " + config.tenant_access_token(),
        "Content-Type": "application/json; charset=utf-8"
    }
    rsp_dict = post_req(url, headers, req_body)
    code = rsp_dict.get("code", -1)
    data = rsp_dict.get("data")
    if code == 0:
        href = data.get("url")
        update_file_open(data.get("objToken"), config)
        jsonObjects = {
            "msg_type": "text",
            "content": json.dumps({"text": f"[{title}]({href})"}),
        }
        # set_user_editable(data["objToken"], "ou_7fd3ab84d15e9d3e6f95e475bc7ea76b", config)
        post_req(
            "https://open.feishu.cn/open-apis/bot/v2/hook/92de881a-09b5-4df4-a95c-610927c4d9fc", 
            {"Content-Type": "application/json; charset=utf-8"},
            jsonObjects
        )


if __name__ == '__main__':
    if len(sys.argv) > 1:
        if sys.argv[1] == "set_user_editable":
            set_user_editable(sys.argv[2], sys.argv[3], config)
    else:
        print(show_group_chat(config))
    # set_user_editable("doccnyCEvTLBwnPWIra0gsfkTVg", "ou_7fd3ab84d15e9d3e6f95e475bc7ea76b", config)
